package com.zzyl.nursing.service.impl;

import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Arrays;

/**
 * 设备表Service业务层处理
 *
 * @author zhengnuli
 * @date 2025-01-18
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private Client client;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     *
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

//    @Override
//    public void syncProductList() {
//        QueryProductListRequest request = new QueryProductListRequest();
//        request.setPageSize(200);
//        request.setCurrentPage(1);
//        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
//
//        QueryProductListResponse response;
//
//        try {
//            response = client.queryProductList(request);
//        } catch (Exception e) {
//            throw new BaseException("物联网接口 - 查询产品，同步失败");
//        }
//
//        if (!response.getBody().success) {
//            throw new BaseException("物联网接口 - 查询产品，调用失败");
//        }
//
//        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));
//    }

    @Override
    public void syncProductList() {
        QueryProductListRequest request = new QueryProductListRequest();
        request.setPageSize(200);
        request.setCurrentPage(1);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryProductListResponse response;

        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }

        if (!response.getBody().success) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }

        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));
    }


//    @Override
//    public List<ProductVo> allProduct() {
//        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
//        if (StringUtils.isEmpty(jsonStr)) {
//            return Collections.emptyList();
//        }
//        return JSONUtil.toList(jsonStr, ProductVo.class);
//    }

    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);

        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }
@Override
public void registerDevice(DeviceDto deviceDto) {
        //判断设备名称是否重复
    LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
    long count = count(queryWrapper);
    if (count > 0) {
        throw new BaseException("设备名称已存在，请重新取名");
        //先以该名称精确查询，看是否能找到对应的已存在的设备
        //大于0就是存在
    }
    RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
    registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
    RegisterDeviceResponse response;

    try {
        response = client.registerDevice(registerDeviceRequest);
    } catch (Exception e) {
        throw new BaseException("物联网接口 - 注册设备，调用失败");
    }

    if (!response.getBody().success) {
        throw new RuntimeException(response.getBody().getErrorMessage());
        //如果代码正常到这里运行完，不报错，表示该对象已经存入第三方的数据库
    }

    QueryProductRequest queryProductRequest = new QueryProductRequest();
    queryProductRequest.setProductKey(deviceDto.getProductKey());
    queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
    QueryProductResponse queryProductResponse;

    try {
        queryProductResponse = client.queryProduct(queryProductRequest);
    } catch (Exception e) {
        throw new BaseException("物联网接口 - 查询产品，调用失败");
    }
    if (!queryProductResponse.getBody().success) {
        throw new BaseException("物联网接口 - 查询产品，调用失败");
//        向第三方数据库查询该产品的信息
    }

    Device device = BeanUtil.toBean(deviceDto, Device.class);
    device.setProductName(queryProductResponse.getBody().getData().productName);

    if (device.getLocationType().equals(0)) {
        device.setPhysicalLocationType(-1);
    }

    device.setIotId(response.getBody().getData().getIotId());

    try {
        deviceMapper.insertDevice(device);
    } catch (Exception e) {
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setDeviceName(device.getDeviceName());
        deleteDeviceRequest.setProductKey(device.getProductKey());
        deleteDeviceRequest.setIotId(device.getIotId());
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception exception) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
        throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        //尝试插入该设备到自己的数据库，并且检测错误，如果出现了错误，那么已经成功插入第三方的内容也要删掉
    }


}


//    @Override
//    public void registerDevice(DeviceDto deviceDto) {
//        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
//        long count = count(queryWrapper);
//        if (count > 0) {
//            throw new BaseException("设备名称已经存在，请重新输入");
//        }
//
//        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
//        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
//        RegisterDeviceResponse response;
//        try {
//            response = client.registerDevice(registerDeviceRequest);
//        } catch (Exception e) {
//            throw new BaseException("物联网接口 - 注册设备，调用失败");
//        }
//
//        if (!response.getBody().success) {
//            throw new RuntimeException(response.getBody().getErrorMessage());
//        }
//
//        QueryProductRequest queryProductRequest = new QueryProductRequest();
//        queryProductRequest.setProductKey(deviceDto.getProductKey());
//        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
//        QueryProductResponse queryProductResponse;
//        try {
//            queryProductResponse = client.queryProduct(queryProductRequest);
//        } catch (Exception e) {
//            throw new BaseException("物联网接口 - 查询产品，调用失败");
//        }
//        if (!queryProductResponse.getBody().success) {
//            throw new BaseException("物联网接口 - 查询产品，调用失败");
//        }
//
//        Device device = BeanUtil.toBean(deviceDto, Device.class);
//        device.setProductName(queryProductResponse.getBody().getData().productName);
//
//        if (device.getLocationType().equals(0)) {
//            device.setPhysicalLocationType(-1);
//        }
//
//        device.setIotId(response.getBody().getData().getIotId());
//
//        try {
//            deviceMapper.insertDevice(device);
//        } catch (Exception e) {
//            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
//            deleteDeviceRequest.setDeviceName(device.getDeviceName());
//            deleteDeviceRequest.setProductKey(device.getProductKey());
//            deleteDeviceRequest.setIotId(device.getIotId());
//            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
//
//            try {
//                client.deleteDevice(deleteDeviceRequest);
//            } catch (Exception ex) {
//                throw new BaseException("物联网接口 - 删除设备，调用失败");
//            }
//            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
//        }
//
//    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {

        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotId(deviceDto.getIotId());
        queryDeviceDetailRequest.setProductKey(deviceDto.getProductKey());
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;

        try {
            response = client.queryDeviceDetail(queryDeviceDetailRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备，调用失败");
        }
        if (!response.getBody().success) {
            throw new RuntimeException("物联网接口 - 查询设备，调用失败");
        }

        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);

        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());

        return deviceVo;
    }

    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse queryDevicePropertyStatusResponse;

        try {
            queryDevicePropertyStatusResponse = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性状态，调用失败");
        }
        if (!queryDevicePropertyStatusResponse.getBody().success) {
            throw new BaseException(queryDevicePropertyStatusResponse.getBody().getErrorMessage());
        }
        return AjaxResult.success(queryDevicePropertyStatusResponse.getBody().getData());
    }

    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;

        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }


}
